package edu.ncsu.csc.ip.client.timer;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import edu.ncsu.csc.ip.client.PeerClient;
import edu.ncsu.csc.ip.client.RFCBean;
import edu.ncsu.csc.ip.client.RFCIndex;
import edu.ncsu.csc.ip.client.protocol.ProtocolClientImpl;
import edu.ncsu.csc.ip.common.Log;

/**
 * Class <code></code>
 * 
 * 
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */

public class TTLUpdateTask extends TimerTask {

	private RFCIndex rfcIndex;
	private PeerClient peerClient;

	public TTLUpdateTask(RFCIndex rfcIndex, PeerClient peerClient) {
		this.rfcIndex = rfcIndex;
		this.peerClient = peerClient;
	}

	@Override
	public void run() {
		try {
			peerClient.runCommand(ProtocolClientImpl.KEEPALIVE);
		} catch (IOException e) {
			Log.println("KEEPALIVE Failed!");
		}
		Map<Integer, List<RFCBean>> rfcIndexMap = rfcIndex.getRfcIndexMap();
		for (List<RFCBean> rfcBeanList : rfcIndexMap.values()) {
			for (RFCBean rfcBean : rfcBeanList) {
				int ttl;
				if (rfcBean.getTtl() != null
						&& (ttl = rfcBean.getTtl()) > RFCIndex.TTL_UPDATE_INTERVAL)
					rfcBean.setTtl(ttl - RFCIndex.TTL_UPDATE_INTERVAL);
				else {
					rfcIndexMap.remove(rfcIndexMap);
					// rfcBean.setTtl(0);
				}
			}
		}
	}
}
